<?php
/**
 * Created by PhpStorm.
 * User: 江雪
 * Date: 2019/05/29
 * Time: 17:01
 */
namespace app\v2\controller;
use app\common\controller\Checking;
use app\common\controller\ThumImage;
use Endroid\QrCode\QrCode;
use think\Controller;
use think\Db;
use think\Response;

class Code extends Base
{
    protected $uid;
    protected $url;
    protected $bg;
    protected $bgth;
    protected $bgkor;
    protected $bgen;
    protected $bgjp;
    protected $default_head;
    public function __construct(\think\Request $request = null)
    {
        parent::__construct($request);
        $this->uid=$this->userId;
        $this->url=API_URL.'/';#后端域名
        $this->bg='assets/img/qrcode.png';#背景图
        $this->bgen='assets/img/qrcodeen.png';#背景图
        $this->default_head=$this->url.'assets/img/head.png';#默認頭像
    }

    /**
     * 推广二维码
     * @return \think\response\Json
     */
    public function code(){
        $user=Db::name('users')->where(['id'=>$this->uid])->field('language,qrcode_image,uuid,invite_code')->find();
        $tz_url=WEB_URL.'/register?puid='.$user['invite_code'];
//        if ($user['qrcode_image']!='' ||$user['qrcode_image']!=null){
//            $data=[
//                'qrcode'=>$this->url.$user['qrcode_image'],
//                'invite_code'=>$user['invite_code'],
//                'url'=>$tz_url
//            ];
//            Checking::response(200,'获取成功',$data);
//        }
        // 前景色
        list($r, $g, $b) = sscanf("#ffffff", "#%02x%02x%02x");
        $foregroundcolor = ['r' => $r, 'g' => $g, 'b' => $b];
        // 背景色
        list($r, $g, $b) = sscanf("#000000", "#%02x%02x%02x");
        $backgroundcolor = ['r' => $r, 'g' => $g, 'b' => $b];
        $qrCode = new QrCode();
        $qrCode
            ->setText($tz_url)
            ->setSize(400)
            ->setPadding(5)
            ->setErrorCorrection('medium')
            ->setForegroundColor($foregroundcolor)
            ->setBackgroundColor($backgroundcolor)
            ->setLogoSize(10)
//            ->setLabelFontPath(ROOT_PATH . 'public/assets/fonts/fzltxh.ttf')
//            ->setLabel('123546')
//            ->setLabelFontSize(12)
            ->setLabelHalign(0)
            ->setLabelValign(3)
            ->setImageType(QrCode::IMAGE_TYPE_PNG);
        $uid=$this->uid;
        switch ($user['language']){
            case 1:
                $qrCode->save('userimg/qrcode'.$uid.'.png');
                $img=$this->h_code($user['uuid'],$this->bg,'zh','userimg/qrcode'.$uid.'.png','userimg/qrcode'.$uid.'.png');
                break;
            case 2:
                $qrCode->save('userimg/qrcode_en'.$uid.'.png');
                $img=$this->h_code($user['uuid'],$this->bgen,'en','userimg/qrcode_en'.$uid.'.png','userimg/qrcode_en'.$uid.'.png');
                break;
        }
        Db::name('users')->where(['id'=>$this->uid])->setField('qrcode_image',$img);
        $data=[
            'qrcode'=>$this->url.$img,
            'invite_code'=>$user['invite_code'],
            'url'=>$tz_url
        ];
        Checking::response(200,'获取成功',$data);
    }

    /**
     * @param $uid 用戶id
     * @param $head_path 頭像路徑
     * @param string $teststr 用戶昵称
     * $teststr1 uuid
     * @return string
     */
    public function h_code($teststr,$bg,$language,$bg_er,$new_fileNamge){
        $code=$bg_er;
        $path_1=  $this->url.$bg;//背景图
        $width=getimagesize($path_1);
        $path_2 = $this->url.$code;   //二维码图片
//        $image_1 = imagecreatefromjpeg($path_1);
        $image_1 = imagecreatefrompng($path_1);
        $image_2 = imagecreatefrompng($path_2);
        // 创建真彩画布
        $image_3 = imageCreatetruecolor(imagesx($image_1),imagesy($image_1));
        // 为真彩画布创建白色背景
        $color = imagecolorallocate($image_3, 255, 255, 255);
        imagefill($image_3, 0, 0, $color);
        // 设置透明
        $font=ROOT_PATH . 'public/assets/fonts/fzltxh.ttf';
        // 复制图片一到真彩画布中（重新取样-获取透明图片）
        $im = imagecreatetruecolor(10, 10);
        $black = imagecolorallocate($im, 255, 255, 255);
        mb_internal_encoding("UTF-8"); // 设置编码
        $fontBox = imagettfbbox(20, 0, $font, $teststr);
//        $fontBox1 = imagettfbbox(20, 0, $font, $teststr1);
        switch ($language){
            case 'zh':
                imagettftext($image_1, 26, 0, ($width[0]-$fontBox[2])/2-50, 650, $black,$font , $teststr);//将文字写到图片中
                break;
            case 'en':
                imagettftext($image_1, 18, 0, ($width[0]-$fontBox[2])/2+40, 650, $black,$font , $teststr);//将文字写到图片中
                break;
        }
//        imagettftext($image_1, 26, 0, ($width[0]-$fontBox1[2])/2, 220, $black,$font , $teststr1);//将文字写到图片中
        imagecopyresampled($image_3, $image_1, 0, 0, 0, 0, imagesx($image_1), imagesy($image_1), imagesx($image_1), imagesy($image_1));
        // 与图片二合成
        imagecopymerge($image_3, $image_2, 170, 700, 0, 0, imagesx($image_2), imagesy($image_2), 100);
        // 输出合成图片
        imagepng($image_3,$new_fileNamge);
        #获取图片的宽高
//        $url = $head_path;
//        if( @fopen( $url, 'r' ) )    {
//            $head_paths=$head_path;
//        }else{
//            $head_paths=$this->default_head;
//        }
//        $head = $this->yuanjiao($head_paths);#处理图像圆角
        // 为真彩画布创建白色背景
//        $color = imagecolorallocate($head, 223,253,253);
//        imagefill($head, 0, 0, $color);
        // 设置透明
//        imagesavealpha($head, true);
        // 与图片二合成
//        imagecopymerge($image_3, $head, ($width[0]-80)/2, 30, 0, 0, imagesx($head), imagesy($head), 100);
        // 输出合成图片
//        imagepng($image_3,'userimg/qrcode'.$uid.'.png');
        $source =  $code;//原图片名称
        $dst_img = $code;//压缩后图片的名称
        $percent = 0.5;  #原图压缩，不缩放，但体积大大降低
        $image = (new ThumImage($source,$percent))->compressImg($dst_img);
        return $code;
    }
    #头像圆化
    function yuanjiao($url){
        $sw = getimagesize($url)[0];
        $sh=getimagesize($url)[1]; // original size
        $w=98; $h=100;
        $original_path= $url;
        $src = imagecreatefromstring(file_get_contents($original_path));
        $newpic = imagecreatetruecolor($w,$h);
        imagecopyresampled($src, $src, 0,0, 0,0, $w, $h, $sw, $sh);//缩放图片
        imagealphablending($newpic,false);
        $transparent = imagecolorallocatealpha($newpic, 255, 255, 255, 127);
        $r=$w/2;
        for($x=0;$x<$w;$x++) {
            for ($y = 0; $y < $h; $y++) {
                $c = imagecolorat($src, $x, $y);
                $_x = $x - $w / 2;
                $_y = $y - $h / 2;
                if ((($_x * $_x) + ($_y * $_y)) < ($r * $r)) {
                    imagesetpixel($newpic, $x, $y, $c);
                } else {
                    imagesetpixel($newpic, $x, $y, $transparent);
                }
            }
        }
        return $newpic;
    }
    /**
     *  blog:http://www.zhaokeli.com
     * 处理成圆图片,如果图片不是正方形就取最小边的圆半径,从左边开始剪切成圆形
     * @param  string $imgpath [description]
     * @return [type]          [description]
     */
    function yuan_img($imgpath = './tx.jpg') {
        $ext     = pathinfo($imgpath);
        $src_img = null;
        switch ($ext['extension']) {
            case 'jpg':
                $src_img = imagecreatefromjpeg($imgpath);
                break;
            case 'png':
                $src_img = imagecreatefrompng($imgpath);
                break;
        }
//        $wh  = getimagesize($imgpath);
//        $w   = $wh[0];
//        $h   = $wh[1];
        $w=98; $h=100;
        $w   = min($w, $h);
        $h   = $h;
        $img = imagecreatetruecolor($w, $h);
        //这一句一定要有
        imagesavealpha($img, true);
        //拾取一个完全透明的颜色,最后一个参数127为全透明
        $bg = imagecolorallocatealpha($img, 255, 255, 255, 127);
        imagefill($img, 0, 0, $bg);
        $r   = $w / 2; //圆半径
        for ($x = 0; $x < $w; $x++) {
            for ($y = 0; $y < $h; $y++) {
                $rgbColor = imagecolorat($src_img, $x, $y);
                if (((($x - $r) * ($x - $r) + ($y - $r) * ($y - $r)) < ($r * $r))) {
                    imagesetpixel($img, $x, $y, $rgbColor);
                }
            }
        }
        return $img;
    }
}